import { resolveAssetUrl } from '@/constants/config';
import { apiRequest } from './api';

type ApiAsset = {
  preview_url?: string | null;
  thumb_url?: string | null;
  original_url?: string | null;
};

type ApiProductLite = {
  id: number;
  title?: string | null;
  price?: number | null;
  cover_asset?: ApiAsset | null;
  cover_image?: string | null;
  images?: Array<
    | { asset?: ApiAsset | null }
    | { preview_url?: string | null; thumb_url?: string | null; original_url?: string | null }
    | { url?: string | null }
  >;
};

export type ProductThumbnail = {
  id: number;
  title: string;
  price: number | null;
  imageUrl: string | null;
};

const productCache = new Map<number, ProductThumbnail>();

function pickAssetUrl(asset?: ApiAsset | null): string {
  if (!asset) {
    return '';
  }
  const url = asset.preview_url || asset.thumb_url || asset.original_url || '';
  return resolveAssetUrl(url || '');
}

function resolvePrimaryImage(product: ApiProductLite): string | null {
  if (product.cover_image) {
    const resolved = resolveAssetUrl(product.cover_image);
    if (resolved) {
      return resolved;
    }
  }

  const cover = pickAssetUrl(product.cover_asset);
  if (cover) {
    return cover;
  }

  if (Array.isArray(product.images)) {
    for (const image of product.images) {
      let candidate = '';
      if ('asset' in (image as any)) {
        candidate = pickAssetUrl((image as any).asset);
      } else if ('preview_url' in (image as any) || 'thumb_url' in (image as any) || 'original_url' in (image as any)) {
        const assetLike = image as Partial<ApiAsset>;
        candidate = resolveAssetUrl(assetLike.preview_url || assetLike.thumb_url || assetLike.original_url || '');
      } else if ('url' in (image as any)) {
        candidate = resolveAssetUrl((image as any).url || '');
      }
      if (candidate) {
        return candidate;
      }
    }
  }

  return null;
}

export function mapProductToThumbnail(product: ApiProductLite): ProductThumbnail {
  const thumbnail: ProductThumbnail = {
    id: product.id,
    title: product.title?.trim() || '未命名商品',
    price: typeof product.price === 'number' ? product.price : null,
    imageUrl: resolvePrimaryImage(product),
  };
  productCache.set(product.id, thumbnail);
  return thumbnail;
}

export async function fetchProductThumbnail(id: number): Promise<ProductThumbnail> {
  if (productCache.has(id)) {
    return productCache.get(id)!;
  }

  const product = await apiRequest<ApiProductLite>(`/products/${id}`);
  return mapProductToThumbnail(product);
}
